import { _decorator, Component, Node, resources, Prefab, instantiate } from 'cc';
import { SingletonComponent } from './framework/SingletonComponent.mjs';
import { GameView } from './GameView';
import { EndingView } from './EndingView';
import { Playable, playable } from "./framework/Playable.mjs";

const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends SingletonComponent {
    @property(Node)
    private uiRoot: Node = null;

    private gameView: GameView = null;
    private endView: EndingView = null;


    private _gameState: number = 0;

    public get gameState(): number {
        return this._gameState;
    }
    public set gameState(value: number) {
        this._gameState = value;
    }


    start() {
        this.showGameView();

    }

    showGameView() {
        if (!this.gameView) {
            resources.load("prefabs/GameView", Prefab, (err, prefab) => {
                const newNode = instantiate(prefab);
                this.uiRoot.addChild(newNode);
                this.gameView = newNode.getComponent(GameView);
                this.gameView.eventSystem.on(GameView.StateChangedEvent, this.onGameStateChanged, this);
            });
        } else {
            this.gameView.showView();
        }
    }

    onGameStateChanged(state: number) {
        this.gameState = state;
        if (this.gameState === 2) {
            this.gameView.hideView();
            this.showEndingView();
        }
    }

    showEndingView() {
        playable.showEnding(true);
        if (!this.endView) {
            resources.load("prefabs/endingView", Prefab, (err, prefab) => {
                const newNode = instantiate(prefab);
                this.uiRoot.addChild(newNode);
            });
        } else {
            this.endView.showView();
        }
    }

    update(deltaTime: number) {
        
    }
}


